package org.longteng.security.service.impl;

import org.longteng.dao.mapper.AuthUserMapper;
import org.longteng.dao.mapper.OauthClientMapper;
import org.longteng.dao.model.AuthUser;
import org.longteng.dao.model.OauthClient;
import org.longteng.security.service.AuthUserService;
import org.longteng.security.utils.SM3Utils;
import org.longteng.security.vo.AuthorizationUserVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.security.auth.message.AuthException;

/**
 * appid与用户帐号验证服务层实现类
 * @author hymn.com
 * @date 2022/12/17 10:00:00
 */
@Slf4j
@Service
public class AuthUserServiceImpl implements AuthUserService {
    @Autowired(required = false)
    private OauthClientMapper authClientMapper;
    @Autowired(required = false)
    private AuthUserMapper authUserMapper;

    /**
     * 验证客户appid，以便生成token
     * // 1验证sign是否合法，2验证appid是否有效，3验证用户是否有效
     * @param authUserVo
     * @return 返回appi的定义与token与过期时间
     */
    @Override
    public OauthClient verifySignAuthUser(AuthorizationUserVo authUserVo) throws AuthException {
        log.debug("查询appId数据，{}", authUserVo.getAppId());
        if(authClientMapper == null || authUserMapper == null) {

        }

        OauthClient authClient = authClientMapper.getActiveClientApp(authUserVo.getAppId());
        if (authClient == null) {
            if(log.isDebugEnabled()) {
                log.debug("appid未定义。{}", authUserVo.getAppId());
            }
            log.error("验证客户appid错误。{}", authUserVo.getAppId());
            throw new AuthException("appid未定义。");
        }
        String srcStr = authClient.getAppId()+authClient.getAppSecret();
        if(log.isDebugEnabled()) {
            log.debug("开始判断源数据与加密数据是否一致。appIdAppSecret:{},Sign:{}", srcStr,authUserVo.getSign());
        }
        boolean verifyFlag = SM3Utils.verify(srcStr, authUserVo.getSign());  // 验证sign是否合法
        if(log.isDebugEnabled()) {
            log.debug("开始判断源数据与加密数据是否一致。appIdAppSecret:{},verifyFlag:{}", srcStr,verifyFlag);
        }
        if(! verifyFlag) {
            log.error("sign不合法。appIdAppSecret:{}", srcStr);
            throw new AuthException("sign不合法。");
        }

        AuthUser user = authUserMapper.getActiveUser(authUserVo.getUser());
        if (user == null) {
            if(log.isDebugEnabled()) {
                log.debug("用户验证错误，不存在。{}", authUserVo.getUser());
            }
            log.error("用户验证错误。{}", authUserVo.getUser());
            throw new AuthException("用户验证错误。");
        }
        return authClient;
    }
}
